//
// (C) Copyright 2009 Irantha Suwandarathna (irantha@gmail.com)
// All rights reserved.
//

/* Copyright (c) 2001-2008, The HSQL Development Group
 * All rights reserved.
 *
 * Redistribution and use _in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
 * Redistributions of source code must retain the above copyright notice, this
 * list of conditions and the following disclaimer.
 *
 * Redistributions _in binary form must reproduce the above copyright notice,
 * this list of conditions and the following disclaimer _in the documentation
 * and/or other materials provided with the distribution.
 *
 * Neither the name of the HSQL Development Group nor the names of its
 * contributors may be used to endorse or promote products derived from this
 * software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 * ARE DISCLAIMED. IN NO EVENT SHALL HSQL DEVELOPMENT GROUP, HSQLDB.ORG,
 * OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using EffiProz.Core.Lib;
using EffiProz.Core.DataTypes;
using EffiProz.Core.Indexes;
using EffiProz.Core.Errors;
using EffiProz.Core.Persist;
using EffiProz.Core.Rights;

namespace EffiProz.Core
{

    /**
     * Maintains a sequence of numbers.
     *
     * @author  fredt@users
     * @since 1.7.2
     * @version 1.7.2
     */
    public class NumberSequence : SchemaObject
    {

        public static NumberSequence[] emptyArray = new NumberSequence[] { };

        //
        public QNameManager.QName name;

        // present value
        private long currValue;

        // last value
        private long lastValue;

        // limit state
        private bool limitReached;

        // original start value - used in CREATE and ALTER commands
        private long startValue;
        private long minValue;
        private long maxValue;
        private long increment;
        private SqlType dataType;
        private bool _isCycle;
        private bool _isAlways;
        private bool restartValueDefault;

        public NumberSequence()
        {

            try
            {
                setDefaults(null, SqlType.SQL_BIGINT);
            }
            catch (CoreException ) { }
        }

        public NumberSequence(QNameManager.QName name, SqlType type)
        {
            setDefaults(name, type);
        }

        public void setDefaults(QNameManager.QName name, SqlType type)
        {

            this.name = name;
            dataType = type;
            this.name = name;
            dataType = type;

            long min;
            long max;

            switch (dataType.typeCode)
            {

                case Types.SQL_SMALLINT:
                    max = short.MaxValue;
                    min = short.MinValue;
                    break;

                case Types.SQL_INTEGER:
                    max = int.MaxValue;
                    min = int.MinValue;
                    break;

                case Types.SQL_BIGINT:
                    max = long.MaxValue;
                    min = long.MinValue;
                    break;

                case Types.SQL_NUMERIC:
                case Types.SQL_DECIMAL:
                    if (type.scale == 0)
                    {
                        max = long.MaxValue;
                        min = long.MinValue;

                        break;
                    }

                    throw Error.error(ErrorCode.X_42565);

                default:
                    throw Error.error(ErrorCode.X_42565);
            }

            minValue = min;
            maxValue = max;
            increment = 1;
        }

        /**
         * constructor with initial value and increment;
         */
        public NumberSequence(QNameManager.QName name, long value, long increment,
                              SqlType type)
            : this(name, type)
        {



            setStartValue(value);
            setIncrement(increment);
        }

        public int getType()
        {
            return SchemaObjectTypes.SEQUENCE;
        }

        public QNameManager.QName getName()
        {
            return name;
        }

        public QNameManager.QName getCatalogName()
        {
            return name.schema.schema;
        }

        public QNameManager.QName getSchemaName()
        {
            return name.schema;
        }

        public Grantee getOwner()
        {
            return name.schema.owner;
        }

        public OrderedHashSet getReferences()
        {
            return new OrderedHashSet();
        }

        public OrderedHashSet getComponents()
        {
            return null;
        }

        public void compile(Session session, SchemaObject parentObject) { }

        public String getSQL()
        {

            StringBuilder sb = new StringBuilder(128);

            if (name == null)
            {
                sb.Append(Tokens.T_GENERATED).Append(' ');

                if (isAlways())
                {
                    sb.Append(Tokens.T_ALWAYS);
                }
                else
                {
                    sb.Append(Tokens.T_BY).Append(' ').Append(Tokens.T_DEFAULT);
                }

                sb.Append(' ').Append(Tokens.T_AS).Append(' ').Append(
                    Tokens.T_IDENTITY).Append(Tokens.T_OPENBRACKET);
            }
            else
            {
                sb.Append(Tokens.T_CREATE).Append(' ');
                sb.Append(Tokens.T_SEQUENCE).Append(' ');
                sb.Append(getName().getSchemaQualifiedStatementName()).Append(' ');
                sb.Append(Tokens.T_AS).Append(' ');
                sb.Append(getDataType().getNameString()).Append(' ');
            }

            //
            sb.Append(Tokens.T_START).Append(' ');
            sb.Append(Tokens.T_WITH).Append(' ');
            sb.Append(startValue);

            if (getIncrement() != 1)
            {
                sb.Append(' ').Append(Tokens.T_INCREMENT).Append(' ');
                sb.Append(Tokens.T_BY).Append(' ');
                sb.Append(getIncrement());
            }

            if (!hasDefaultMinMax())
            {
                sb.Append(' ').Append(Tokens.T_MINVALUE).Append(' ');
                sb.Append(getMinValue());
                sb.Append(' ').Append(Tokens.T_MAXVALUE).Append(' ');
                sb.Append(getMaxValue());
            }

            if (isCycle())
            {
                sb.Append(' ').Append(Tokens.T_CYCLE);
            }

            if (name == null)
            {
                sb.Append(Tokens.T_CLOSEBRACKET);
            }

            return sb.ToString();
        }

        public String getRestartSQL()
        {

            StringBuilder sb = new StringBuilder(128);

            sb.Append(Tokens.T_ALTER).Append(' ');
            sb.Append(Tokens.T_SEQUENCE);
            sb.Append(' ').Append(name.getSchemaQualifiedStatementName());
            sb.Append(' ').Append(Tokens.T_RESTART);
            sb.Append(' ').Append(Tokens.T_WITH).Append(' ').Append(peek());

            return sb.ToString();
        }

        public static String getRestartSQL(Table t)
        {

            String colname = t.getColumn(t.identityColumn).getName().statementName;
            NumberSequence seq = t.identitySequence;
            StringBuilder sb = new StringBuilder(128);

            sb.Append(Tokens.T_ALTER).Append(' ').Append(Tokens.T_TABLE);
            sb.Append(' ').Append(t.getName().getSchemaQualifiedStatementName());
            sb.Append(' ').Append(Tokens.T_ALTER).Append(' ');
            sb.Append(Tokens.T_COLUMN);
            sb.Append(' ').Append(colname);
            sb.Append(' ').Append(Tokens.T_RESTART);
            sb.Append(' ').Append(Tokens.T_WITH).Append(' ').Append(seq.peek());

            return sb.ToString();
        }

        public SqlType getDataType()
        {
            return dataType;
        }

        public long getIncrement()
        {
            return increment;
        }

        public long getStartValue()
        {
            lock (this)
            {
                return startValue;
            }
        }

        public long getMinValue()
        {
            lock (this)
            {
                return minValue;
            }
        }

        public long getMaxValue()
        {
            lock (this)
            {
                return maxValue;
            }
        }

        public bool isCycle()
        {
            lock (this)
            {
                return _isCycle;
            }
        }

        public bool isAlways()
        {
            lock (this)
            {
                return _isAlways;
            }
        }

        public bool hasDefaultMinMax()
        {
            lock (this)
            {
                long min;
                long max;

                switch (dataType.typeCode)
                {

                    case Types.SQL_SMALLINT:
                        max = short.MaxValue;
                        min = short.MinValue;
                        break;

                    case Types.SQL_INTEGER:
                        max = int.MaxValue;
                        min = int.MinValue;
                        break;

                    case Types.SQL_BIGINT:
                        max = long.MaxValue;
                        min = long.MinValue;
                        break;

                    case Types.SQL_NUMERIC:
                    case Types.SQL_DECIMAL:
                        max = long.MaxValue;
                        min = long.MinValue;
                        break;

                    default:
                        throw Error.runtimeError(ErrorCode.U_S0500, "NumberSequence");
                }


                return minValue == min && maxValue == max;
            }
        }

        public void setStartValue(long value)
        {

            lock (this)
            {
                if (value < minValue || value > maxValue)
                {
                    throw Error.error(ErrorCode.X_42597);
                }

                startValue = value;
                currValue = lastValue = startValue;
            }
        }

        public void setMinValue(long value)
        {
            lock (this)
            {
                checkInTypeRange(value);

                if (value >= maxValue || currValue < value)
                {
                    throw Error.error(ErrorCode.X_42597);
                }

                minValue = value;
            }
        }

        public void setDefaultMinValue()
        {
            lock (this)
            {
                minValue = getDefaultMinOrMax(false);
            }
        }

        public void setMaxValue(long value)
        {
            lock (this)
            {

                checkInTypeRange(value);

                if (value <= minValue || currValue > value)
                {
                    throw Error.error(ErrorCode.X_42597);
                }

                maxValue = value;
            }
        }

        public void setDefaultMaxValue()
        {
            lock (this)
            {
                maxValue = getDefaultMinOrMax(true);
            }
        }

        public void setIncrement(long value)
        {
            lock (this)
            {
                if (value < short.MinValue / 2 || value > short.MaxValue / 2)
                {
                    throw Error.error(ErrorCode.X_42597);
                }

                increment = value;
            }
        }

        public void setCurrentValueNoCheck(long value)
        {
            lock (this)
            {
                checkInTypeRange(value);

                currValue = lastValue = value;
            }
        }

        public void setStartValueNoCheck(long value)
        {
            lock (this)
            {
                checkInTypeRange(value);

                startValue = value;
                currValue = lastValue = startValue;
            }
        }

        public void setStartValueDefault()
        {
            lock (this)
            {
                restartValueDefault = true;
            }
        }

        public void setMinValueNoCheck(long value)
        {
            lock (this)
            {
                checkInTypeRange(value);

                minValue = value;
            }
        }

        public void setMaxValueNoCheck(long value)
        {
            lock (this)
            {
                checkInTypeRange(value);

                maxValue = value;
            }
        }

        public void setCycle(bool value)
        {
            lock (this)
            {
                _isCycle = value;
            }
        }

        public void setAlways(bool value)
        {
            lock (this)
            {
                _isAlways = value;
            }
        }

        private long getDefaultMinOrMax(bool isMax)
        {

            long min;
            long max;

            switch (dataType.typeCode)
            {

                case Types.SQL_SMALLINT:
                    max = short.MaxValue;
                    min = short.MinValue;
                    break;

                case Types.SQL_INTEGER:
                    max = int.MaxValue;
                    min = int.MinValue;
                    break;

                case Types.SQL_BIGINT:
                    max = long.MaxValue;
                    min = long.MinValue;
                    break;

                case Types.SQL_NUMERIC:
                case Types.SQL_DECIMAL:
                    max = long.MaxValue;
                    min = long.MinValue;
                    break;

                default:
                    throw Error.runtimeError(ErrorCode.U_S0500, "NumberSequence");
            }

            return isMax ? max
                         : min;
        }

        private void checkInTypeRange(long value)
        {

            long min;
            long max;

            switch (dataType.typeCode)
            {

                case Types.SQL_SMALLINT:
                    max = short.MaxValue;
                    min = short.MinValue;
                    break;

                case Types.SQL_INTEGER:
                    max = int.MaxValue;
                    min = int.MinValue;
                    break;

                case Types.SQL_BIGINT:
                    max = long.MaxValue;
                    min = long.MinValue;
                    break;

                case Types.SQL_NUMERIC:
                case Types.SQL_DECIMAL:
                    max = long.MaxValue;
                    min = long.MinValue;
                    break;

                default:
                    throw Error.runtimeError(ErrorCode.U_S0500, "NumberSequence");
            }

            if (value < min || value > max)
            {
                throw Error.error(ErrorCode.X_42597);
            }
        }

        public void checkValues()
        {
            lock (this)
            {
                if (restartValueDefault)
                {
                    currValue = lastValue = startValue;
                    restartValueDefault = false;
                }

                if (minValue >= maxValue || startValue < minValue
                        || startValue > maxValue || currValue < minValue
                        || currValue > maxValue)
                {
                    throw Error.error(ErrorCode.X_42597);
                }
            }
        }

        public NumberSequence duplicate()
        {
            lock (this)
            {
                NumberSequence copy = new NumberSequence();

                copy.name = name;
                copy.startValue = startValue;
                copy.currValue = currValue;
                copy.lastValue = lastValue;
                copy.increment = increment;
                copy.dataType = dataType;
                copy.minValue = minValue;
                copy.maxValue = maxValue;
                copy._isCycle = _isCycle;
                copy._isAlways = _isAlways;

                return copy;
            }
        }

        public void reset(NumberSequence other)
        {
            lock (this)
            {
                name = other.name;
                startValue = other.startValue;
                currValue = other.currValue;
                lastValue = other.lastValue;
                increment = other.increment;
                dataType = other.dataType;
                minValue = other.minValue;
                maxValue = other.maxValue;
                _isCycle = other._isCycle;
                _isAlways = other._isAlways;
            }
        }

        /**
         * getter for a given value
         */
        public long userUpdate(long value)
        {
            lock (this)
            {
                if (value == currValue)
                {
                    currValue += increment;

                    return value;
                }

                if (increment > 0)
                {
                    if (value > currValue)
                    {
                        currValue += ((value - currValue + increment) / increment)
                                     * increment;
                    }
                }
                else
                {
                    if (value < currValue)
                    {
                        currValue += ((value - currValue + increment) / increment)
                                     * increment;
                    }
                }

                return value;
            }
        }

        /**
         * Updates are necessary for text tables
         * For memory tables, the logged and scripted RESTART WITH will override
         * this.
         * No checks as values may have overridden the sequnece defaults
         */
        public long systemUpdate(long value)
        {
            lock (this)
            {
                if (value == currValue)
                {
                    currValue += increment;

                    return value;
                }

                if (increment > 0)
                {
                    if (value > currValue)
                    {
                        currValue = value + increment;
                    }
                }
                else
                {
                    if (value < currValue)
                    {
                        currValue = value + increment;
                    }
                }

                return value;
            }
        }

        public Object getValueObject()
        {
            lock (this)
            {
                long value = getValue();
                Object result;

                switch (dataType.typeCode)
                {

                    default:
                    case Types.SQL_SMALLINT:
                    case Types.SQL_INTEGER:
                        result = ((int)value);
                        break;

                    case Types.SQL_BIGINT:
                        result = (value);
                        break;

                    case Types.SQL_NUMERIC:
                    case Types.SQL_DECIMAL:
                        result = (long)(value);
                        break;
                }

                return result;
            }
        }

        /**
         * principal getter for the next sequence value
         */
        public long getValue()
        {
            lock (this)
            {
                if (limitReached)
                {
                    throw Error.error(ErrorCode.X_2200H);
                }

                long nextValue;

                if (increment > 0)
                {
                    if (currValue > maxValue - increment)
                    {
                        if (_isCycle)
                        {
                            nextValue = minValue;
                        }
                        else
                        {
                            limitReached = true;
                            nextValue = minValue;
                        }
                    }
                    else
                    {
                        nextValue = currValue + increment;
                    }
                }
                else
                {
                    if (currValue < minValue - increment)
                    {
                        if (_isCycle)
                        {
                            nextValue = maxValue;
                        }
                        else
                        {
                            limitReached = true;
                            nextValue = minValue;
                        }
                    }
                    else
                    {
                        nextValue = currValue + increment;
                    }
                }

                long result = currValue;

                currValue = nextValue;

                return result;
            }
        }

        /**
         * reset to start value
         */
        public void reset()
        {
            lock (this)
            {
                // no change if called before getValue() or called twice
                lastValue = currValue = startValue;
            }
        }

        /**
         * get next value without incrementing
         */
        public long peek()
        {
            lock (this)
            {
                return currValue;
            }
        }

        /**
         * reset the wasUsed flag
         */
        public bool resetWasUsed()
        {
            lock (this)
            {
                bool result = lastValue != currValue;

                lastValue = currValue;

                return result;
            }
        }

        /**
         * reset to new initial value
         */
        public void reset(long value)
        {
            lock (this)
            {
                if (value < minValue || value > maxValue)
                {
                    throw Error.error(ErrorCode.X_42597);
                }

                startValue = currValue = lastValue = value;
            }
        }
    }
}
